<template>
  <el-drawer v-model="drawer" @closed="closed">
    <!-- 标题部分 -->
    <template #header>
      <h4>新增</h4>
    </template>
    <template #default>
      <el-form
        ref="form"
        :model="formParams"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="账号" prop="username">
          <el-input placeholder="账号" v-model="formParams.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input placeholder="密码" v-model="formParams.password"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input placeholder="昵称" v-model="formParams.nickName"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formParams.status">
            <el-option
              v-for="(item, index) in statusArr"
              :key="index"
              :label="item"
              :value="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <el-input placeholder="头像" v-model="formParams.avatar"></el-input>
        </el-form-item>
        <el-form-item label="生日">
          <el-input placeholder="生日" v-model="formParams.birthday"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="formParams.roleIds"
            multiple
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in roles"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId + ''"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            type="textarea"
            placeholder="描述"
            v-model="formParams.description"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-input placeholder="排序" v-model="formParams.sort"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            size="default"
            @click="save"
          >
            保存
          </el-button>
          <el-button type="primary" size="default" @click="drawer = false">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { userGetPage, userAdd, userEdit, userDelete } from '@/api/system/user'
import { roleGetAll } from '@/api/system/role'
import { ElMessage } from 'element-plus'

let roles = []
onMounted(async () => {
  let { status, data } = await roleGetAll()

  if (status == 200) {
    roles = data
  }
})

let statusArr = ref<any>(['正常', '冻结'])

const defaultForm = {
  userId: '',
  nickName: '', // 昵称
  password: '', // 密码
  status: '', // 状态（0正常，1冻结）
  username: '', // 账号
  avatar: '', // 头像
  birthday: '', // 生日
  description: '', // 个性签名
  roleIds: '', // 角色ID，多个以逗号隔开
  sort: '', // 排序
}
let formParams = reactive<any>({
  ...defaultForm,
})
const rules = {
  username: [{ required: true, message: '请输入', trigger: 'blur' }],
  password: [{ required: true, message: '请输入', trigger: 'blur' }],
  status: [
    { required: true, type: 'number', message: '请输入', trigger: 'blur' },
  ],
  nickName: [{ required: true, message: '请输入', trigger: 'blur' }],
}

let drawer = ref(false)
let edit = ref(false)
const show = (row) => {
  if (row) {
    edit.value = true

    Object.keys(formParams).forEach((key) => {
      formParams[key] = row[key]
    })
    if (formParams.roleIds && formParams.roleIds.length) {
      formParams.roleIds = formParams.roleIds.split(',')
    } else {
      formParams.roleIds = []
    }
  } else {
    edit.value = false
  }
  drawer.value = true
}

let loading = ref(false)
let form = ref()
//保存按钮的方法
const save = async () => {
  await form.value.validate()
  loading.value = true
  let result: any
  let param = { ...formParams }

  if (param.roleIds && param.roleIds.length) {
    param.roleIds = param.roleIds.join(',')
  } else {
    param.roleIds = ''
  }
  if (edit.value) {
    result = await userEdit(param)
  } else {
    result = await userAdd(param)
  }
  loading.value = false
  if (result.status == 200) {
    ElMessage({
      type: 'success',
      message: '操作成功',
    })
    drawer.value = false
    $emit('callback')
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败',
    })
  }
}

const closed = () => {
  Object.assign(formParams, defaultForm)
}

//组件内部数据对外关闭的，别人不能访问
//如果想让外部访问需要通过defineExpose方法对外暴露
defineExpose({
  show,
})
//自定义事件的方法
let $emit = defineEmits(['callback'])
</script>
